<template>
  <view>
    <u-navbar
      title="房间巡检"
      :background="{ backgroundColor:'#9CE0FF'}"
      :border-bottom="false"
      title-color="#000"
      title-size="37"
    />
    <view v-if="!isTimeout" class="flex flex-column justify-between pb-80 mt-10" id="container" :style="{minHeight:`calc(100vh - ${top}px)`}">
      <u-collapse :accordion="false" :head-style="{marginBottom: 30+'rpx'}" ref="refCollapse">
        <u-collapse-item v-for="(item, index) in equipmentWithHidden" :key="index" :ref="'collapse' + index" v-show="!item.hidden" open>
          <template slot="title">
            <view class="text-center bg-19BE6B br-32 p-lr-22 p-tb-17 color-fff font-bold ml-20">
              <text class="max-w-460 text-ellipsis-2">{{item.deviceName}}</text>
            </view>
          </template>
          <view>
            <check-item
              v-for="(standardListItem,standardListIndex) in item.standardList"
              :key="standardListIndex"
              :standardListItem="standardListItem"
              :hospitalId="hospitalId"
              :workOrderId="workOrderId"
              :deviceName="item.deviceName"
              :workOrderName="item.workOrderName"
              :isUseCache="isUseCache"
              :workOrderDeviceId="workOrderDeviceId"
              :hidden="item.hidden"
              ref="checkItem"
              @formData="formData"
              @uploadCachePicFail="uploadCachePicFail"
              @uploadStatusChange="uploadStatusChange"
              @maskShowOpen="maskShowOpen"
              @exceptionShowOpen="exceptionShowOpen"
            >
            </check-item>
          </view>
        </u-collapse-item>

      </u-collapse>
      <view>
        <view class="w-full flex justify-center mb-30">
          <view class="w-200 h-80 br-10 bg-2DB7F5 color-fff fz-30 text-center lh-80 mr-50"
                v-if="currentPage !== 1"
                @tap.stop="handlePre">上一页</view>
          <view class="w-200 h-80 br-10 bg-2DB7F5 color-fff fz-30 text-center lh-80"
                v-if="currentPage * paginationPageSize < equipmentList.length"
                @tap.stop="handleNext">下一页</view>
        </view>
        <view class="w-full flex justify-center">
          <view class="w-250 h-80 br-10 color-fff bg-2DB7F5 fz-30 text-center lh-80 mr-50" @tap="onClick2Normal">
            <text>一键正常</text>
          </view>
          <view class="w-250 h-80 br-10 bg-19BE6B color-fff fz-30 text-center lh-80" @tap="confirm">
            <text>提交</text>
          </view>
        </view>
      </view>
    </view>
    <!--空照片模态框 -->
    <u-modal border-radius="20" :show-confirm-button="false" :show-title="false" mask-close-able v-model="isEmptyPhoto">
      <view class="h-150 flex align-center justify-center font-bold">
        <image class="mr-20 w-38 h-38" src="@/static/images/mine/error.png"></image>
        <text>请上传照片！</text>
      </view>
    </u-modal>


    <!--是否保存缓存弹窗-->
    <u-modal v-model="isCustomBackModalShow" :show-confirm-button="false" :show-title="false" border-radius="20"
             mask-close-able>
      <view class="w-full flex flex-column align-center p-lr-50">
        <view class="lh-center color-333 fz-30 fw-700 p-tb-42 w-full">修改未提交，是否继续退出该页面？</view>
        <view class="w-full">
          <u-checkbox-group>
            <u-checkbox
                v-model="item.checked"
                v-for="(item, index) in isCache"
                :key="index"
                :name="item.name"
            >{{item.name}}</u-checkbox>
          </u-checkbox-group>
        </view>
        <view class="flex align-center justify-center m-tb-50">
          <view class="border-2D8CF0 w-120 h-60 border-box color-fff bg-2D8CF0 fz-28 text-center lh-60 br-5 mr-50"
                @tap="navigateBack">
            <text>确定</text>
          </view>
          <view class="border-2D8CF0 w-120 h-60 border-box color-2D8CF0 fz-28 text-center lh-60 br-5"
                @tap="isCustomBackModalShow = false">
            <text>取消</text>
          </view>
        </view>
      </view>
    </u-modal>

    <!--是否使用本地缓存弹窗-->
    <u-modal v-model="isUseCacheModal" :show-confirm-button="false" :show-title="false" border-radius="20"
             mask-close-able>
      <view class="w-full flex flex-column align-center p-lr-50">
        <view class="lh-center color-333 fz-30 fw-700 p-tb-42 border-bottom-CCCCCC w-full">本地有缓存，是否使用？</view>
        <view class="flex align-center justify-center m-tb-50">
          <view class="border-2D8CF0 w-120 h-60 border-box color-fff bg-2D8CF0 fz-28 text-center lh-60 br-5 mr-50"
                @tap="useCache(true)">
            <text>确定</text>
          </view>
          <view class="border-2D8CF0 w-120 h-60 border-box color-2D8CF0 fz-28 text-center lh-60 br-5"
                @tap="useCache(false)">
            <text>取消</text>
          </view>
        </view>
      </view>
    </u-modal>

    <!--异常提示模态框-->
    <u-modal border-radius="20" :show-confirm-button="false" :show-title="false" mask-close-able v-model="exceptionShow">
      <view class="min-h-150 p-tb-20 p-lr-20 flex align-center justify-center fz-30 font-bold color-333333">
        <image class="mr-20 min-w-38 w-38 h-38" src="@/static/images/mine/error.png"></image>
        <text>{{modalContent}}</text>
      </view>
    </u-modal>


    <u-mask :show="isShowMask" :mask-click-able="false">
      <view class="flex justify-center align-center h-full color-fff fz-32 font-bold">
        <text>{{maskContent}}</text>
        <u-loading mode="circle"></u-loading>
      </view>
    </u-mask>

    <u-modal border-radius="20" :show-confirm-button="false" :show-title="false" mask-close-able v-model="isOneClickModalShow">
      <view class="h-150 flex align-center justify-center fz-30 font-bold color-333333">
        <image class="mr-20 w-38 h-38" src="@/static/images/mine/success.png"></image>
        <text>已全选正常，请继续填写数值与拍照</text>
      </view>
    </u-modal>

    <!--图片上传中模态框-->
    <!-- #ifndef MP-WEIXIN -->
    <u-modal border-radius="20" :show-confirm-button="false" :show-title="false" v-model="isUploading">
      <view class="h-200 flex flex-column align-center justify-center font-bold color-888888 lh-33 bg-fff">
        <text class="mb-10">图片上传中</text>
        <u-loading mode="circle"></u-loading>
      </view>
    </u-modal>
    <!-- #endif -->

    <!--微信小程序使用cover-view解决textarea层级过高问题-->

    <!-- #ifdef MP-WEIXIN -->
    <cover-view class="fixed top0 w-full min-100vh bg-00000060 flex align-center justify-center z-999" v-show="isUploading" @touchmove.stop.prevent="">
      <cover-view class="h-200 w-600 br-20 text-center lh-200 font-bold color-888888 lh-33 bg-fff">
        图片上传中
      </cover-view>
    </cover-view>
    <!-- #endif -->

    <empty-icon v-if="isTimeout"  content="网络错误"></empty-icon>
  </view>
</template>

<script>
import CheckItem from "./components/CheckItem.vue";
import CollapseItem from "./components/CollapseItem.vue";
import getNavBarHeight from "@/mixins/getNavBarHeight";
import {listWorkOrderDevice} from "@/api/inspection/planDevice";
import {submit} from "@/api/inspection/task";
import {mapGetters} from 'vuex'
import EmptyIcon from "../../components/EmptyIcon/EmptyIcon";

const EXCEPTION_CONTENT = {
  COMMIT_FAIL : '提交失败，请重试',
  INPUT_VALUE_ERROR:'输入值不正确，请重新输入！',
  VALUE_OUT_RANGE: '数值必须在-9999到9999之间！',
  COMMIT_IMGERROR_FAIL : '提交缓存图片与异常失败，请重试',
  INPUT_EMPTY : '请输入异常详情！',
  NETWORK_BAD :'网络环境较差，异常信息已储存，请继续巡检后提交',
  LEAST_CHOOSE_ONE : '请至少选择一个结果！'
}

export default {
  name: "roomCheck",
  components: {EmptyIcon, CollapseItem, CheckItem},
  mixins:[getNavBarHeight],
  onLoad(options){
    this.maskContent = ''
    this.workOrderId = options.workOrderId
    this.hospitalId = options.hospitalId
    this.workOrderDeviceId = options.workOrderDeviceId
    listWorkOrderDevice({roomId:options.roomId, workOrderId:options.workOrderId}).then(res => {
      this.equipmentList = res.data
      this.$nextTick(() => {
        this.$refs.refCollapse.init()
        this.isShowMask = false
      })
    }).catch(err => {
      this.isShowMask = false
      this.isTimeout = true
    })
    this.isUseCacheModal = !!this.checkedCache[this.workOrderDeviceId]
  },
  onBackPress(e){
    if(this.allowBack) return false
    //页面是否被修改
    let isChanged = false
    this.$refs.checkItem.forEach(item => {
      isChanged = item.isChange() || isChanged
    })
    if(isChanged){
      this.isCustomBackModalShow = true
    }else{
      return false
    }
    return true
  },
  data(){
    return {
      isUploading:false,
      equipmentList: [],
      standardResult: [],
      workOrderId: '',
      hospitalId: null,
      isEmptyPhoto: false,//必须上传照片的标准没有上传照片提示
      isCustomBackModalShow: false,//返回按钮确认模态框,
      isShowMask: true,
      maskContent: '',
      allowBack: false,
      isUseCache: undefined, //是否使用缓存
      isUseCacheModal: false, //是否使用缓存弹窗
      isCache: [{
        name: '暂存该页面信息',
        checked: true
      }],
      timer: '',
      exceptionShow: false,
      modalContent: '',
      isTimeout: false,
      isOneClickModalShow: false,
      workOrderDeviceId: '',
      isUploadCachePicSuccess: false,
      currentPage: 1,
    }
  },
  computed: {
    ...mapGetters(['checkedCache', 'paginationUseful', 'paginationPageSize']),
    EXCEPTION_CONTENT(){
      return EXCEPTION_CONTENT
    },
    equipmentWithHidden() {
      return this.equipmentList.map((item, idx) => ({
        ...item,
        hidden: this.paginationUseful && (idx < (this.currentPage - 1) * this.paginationPageSize || idx >= this.currentPage * this.paginationPageSize)
      }))
    }
  },
  methods:{
    exceptionShowOpen({ bool , contentKey}){
      this.exceptionShow = bool
      this.modalContent = this.EXCEPTION_CONTENT[contentKey]
    },
    maskShowOpen(bool){
      this.isShowMask = bool
    },
    uploadStatusChange(bool){
      this.isUploading = bool
    },
    uploadCachePicFail(){
      //this.isShowMask = false
      //this.isUploadCachePicSuccess = false
    },
    onClick2Normal(){
      this.$refs.checkItem.forEach(item => {
        item.onClick2Normal()
      })
      this.isOneClickModalShow = true
    },
    useCache(value){
      this.isUseCache = value
      this.isUseCacheModal = false
    },
    //等待所有折叠项展开后隐藏mask
    collapseDone(index){
      if(index + 1 === this.equipmentList.length){
        this.isShowMask = false
      }
    },
    navigateBack(){
      this.allowBack = true
      //缓存数据
      if(this.isCache[0].checked){
        this.$refs.checkItem.forEach(item => {
          item.setStorage()
        })
      }
      //清空缓存数据
      else{
        this.removeCheckedCache()
      }
      this.$tab.navigateBack()
    },
    removeCheckedCache(){
      let checkedCache = this.checkedCache
      if(checkedCache[this.workOrderDeviceId]){
        delete checkedCache[this.workOrderDeviceId]
      }
      this.$store.commit('SET_CHECKEDCACHE', checkedCache)
    },
    // calcHeight(id){
    //   this.$nextTick(() => {
    //     this.$refs[id][0].calcHeight()
    //   })
    // },
    async handlePre() {
      this.maskContent = ''
      this.isShowMask = true
      await new Promise((resolve) => {
        this.$nextTick(() => {setTimeout(() => {resolve()}, 20)})
      })
      this.currentPage--
      await new Promise((resolve) => {
        this.$nextTick(() => {setTimeout(() => {resolve()}, 20)})
      })
      this.isShowMask = false
    },
    async handleNext() {
      this.maskContent = ''
      this.isShowMask = true
      await new Promise((resolve) => {
        this.$nextTick(() => {setTimeout(() => {resolve()}, 20)})
      })
      this.currentPage++
      await new Promise((resolve) => {
        this.$nextTick(() => {setTimeout(() => {resolve()}, 20)})
      })
      this.isShowMask = false
    },
   async confirm(){
      //input值若是异常值，直接点击提交失去焦点时弹出异常上报弹窗，提交无效
      if(this.standardResult.some(item => {
        return item.isErrorModalShow
      })){
        this.standardResult = []
        return
      }
     this.isUploadCachePicSuccess = true
     this.maskContent = '提交缓存图片、异常中...'
     this.isShowMask = true
      try { //try全部，一次性检查缓存提交和巡检结果提交
        //上传缓存数据，并收集数据，同步做法，减少并行图片上传问题
        for(let item of this.$refs.checkItem){
          await item.emitData()
        }
        this.maskContent = '提交巡检信息中...'
      if(this.standardResult.some(item => {
        return (item.isTakePhoto && !item.ossIdList.length && item.status == 0)
      })){
        this.isEmptyPhoto = true
        this.isShowMask = false
        this.standardResult = []
      }else{
        const res = await submit(this.standardResult)
          if(res.code === 200){
            this.allowBack = true
            this.standardResult = []
            this.isShowMask = false
            this.removeCheckedCache()
            this.$tab.navigateBack()
          }
        }
      } catch(err) {
          this.exceptionShow = true
          this.modalContent = this.EXCEPTION_CONTENT.COMMIT_FAIL
          this.standardResult = []
          this.isShowMask = false
      }
    },
    formData(data){
      this.standardResult.push({...data,workOrderId:this.workOrderId})
    }
  },
  beforeDestroy(){
    clearInterval(this.timer)
  }
}
</script>

<style lang="scss">
page{
  background-color: #fff;
}
</style>
<style lang="scss" scoped>
/deep/ .u-collapse-head {
  padding: 20rpx 0 !important;
  background-color: #E9F8FF;
  margin-left: 20rpx;
  margin-right: 20rpx;
}
/deep/ .u-size-medium{
  background-color: #2D8CF0 !important;
  color: #ffffff !important;
  border-color: #2D8CF0 !important;
  border: 0 !important;
  padding: 0 !important;
  height: 60rpx !important;
  width: 120rpx !important;
}
</style>
